package org.youchan.aco.model;

import java.util.ArrayList;
import java.util.List;


import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;

public class MembersList {
	private ObjectContainer mDatabase;
	private List<MembersListListener>  mListenerList;
	
	public MembersList(String dbFile) {
		mDatabase = Db4o.openFile(dbFile);
		mListenerList = new ArrayList<MembersListListener>();
	}
	
	public void addMember(Member ... member) {
		for (Member m : member) {
			String memberId = m.getMemberId();
			if (memberId != null && !memberId.equals("")) {
				Member query = new Member();
				query.setMemberId(memberId);
				mDatabase.delete(query);
			}
			String twitterId = m.getTwitterId();
			if (twitterId != null && !twitterId.equals("")) {
				Member query = new Member();
				query.setTwitterId(twitterId);
				mDatabase.delete(query);
			}
			mDatabase.set(m);
		}
		fireMembersChangedEvent();
	}
	
	public void removeMemberByMemberId(String memberId) {
		Member query = new Member();
		query.setMemberId(memberId);
		if (mDatabase.get(query).size() > 0) {
			mDatabase.delete(query);
			fireMembersChangedEvent();
		}
	}
	
	public void removeMemberByTwitterId(String twitterId) {
		Member query = new Member();
		query.setTwitterId(twitterId);
		if (mDatabase.get(query).size() > 0) {
			mDatabase.delete(query);
			fireMembersChangedEvent();
		}
	}
	
	public Member getMemberByMemberId(String memberId) {
		Member query = new Member();
		query.setMemberId(memberId);
		ObjectSet<Member> result = mDatabase.get(query);
		if (result.size() == 0) {
			return null;
		}
		return result.get(0);
	}
	
	public Member getMemberByTwitterId(String twitterId) {
		Member query = new Member();
		query.setTwitterId(twitterId);
		ObjectSet<Member> result = mDatabase.get(query);
		if (result.size() == 0) {
			return null;
		}
		return result.get(0);
	}
	
	public Member[] getMembersAsArray() {
		ObjectSet<Member> result = mDatabase.get(new Member());
		return result.toArray(new Member[result.size()]);
	}
	
	public void addMembersListListener(MembersListListener listener) {
		mListenerList.add(listener);
	}
	
	private void fireMembersChangedEvent() {
		for (MembersListListener listener: mListenerList) {
			listener.memberListChanged(this);
		}
	}
	
	public interface MembersListListener {
		public void memberListChanged(MembersList membersList);
	}

}
